/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app.session;

import app.entity.Account;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author RubiLam
 */
@Stateless
public class AccountFacade extends AbstractFacade<Account> {

    @PersistenceContext(unitName = "MySweetHomesPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public AccountFacade() {
        super(Account.class);
    }
    
      public Account checkLogin(Account acc){
        Query qr =  em.createNamedQuery("Account.checkLogin");
        qr.setParameter("username", acc.getUsername());
        qr.setParameter("password", acc.getPassword());
        if(qr.getResultList().size()>0){
             Account ac = (Account) qr.getResultList().get(0);
            return ac;
        }
        return null;
    }

    public boolean register(Account acc) {
        boolean f = false;
        try {

            //utx.begin();
            //create(acc);



            //.commit();


            Query qr = em.createNativeQuery("INSERT INTO Account(username,password,role_id)"
                    + " values(?,?,?)");
            qr.setParameter(1, acc.getUsername());
            qr.setParameter(2, acc.getPassword());
            qr.setParameter(3, acc.getRoleId().getRoleId());

            if (qr.executeUpdate() == 1) {
                try {
                    qr = em.createNativeQuery("INSERT INTO UserInformation(username,fullname,gender,address,email,phone,birthday,avatar)"
                            + " values(?,?,?,?,?,?,?,?)");
                  
                    qr.setParameter(1, acc.getUsername());
                    qr.setParameter(2, acc.getUserInformation().getFullname());
                    qr.setParameter(3, acc.getUserInformation().getGender());
                    qr.setParameter(4, acc.getUserInformation().getAddress());
                    qr.setParameter(5, acc.getUserInformation().getEmail());
                    qr.setParameter(6, acc.getUserInformation().getPhone());
                    qr.setParameter(7, acc.getUserInformation().getBirthday());
                    qr.setParameter(8, acc.getUserInformation().getAvatar());
                   

                    if (qr.executeUpdate() == 1) {
                        f = true;
                    }
                } catch (Exception e) {
                    f = false;
                }
            }

        } catch (Exception e) {
            f = false;
        } finally {
            return f;
        }

    }
}
